import os

from django.conf import settings


from goods.models import GoodsCategory, SKU, GoodsVisitCount


from qingmei_mall.utils.get_category import get_category
from qingmei_mall.utils.breadcrumb import breadcrumd

from django.shortcuts import render




def genarate_detail_html(sku_id):
    # 商品频道分类
    categories = get_category()
    # 面包屑导航
    # 获取库存商品对象
    try:
        sku = SKU.objects.get(id=sku_id)
    except:
        return render(None, '404.html')
    # 库存商品==>三级分类对象
    cat3 = sku.category
    breadcrumb = breadcrumd(cat3)
    # 库存商品信息
    # 查询规格
    # 查询该库存商品对应的规格选项表对象[<7>,<8>]  [8,11]
    # 构建库存商品选项数据与库存商品id的字典
    # skus_dict = {}
    # # 获取所有的库存商品对象
    # skus = SKU.objects.all()
    # for info in skus:
    #     # 获取该库存商品所对应的规格详情对象
    #     specs_list = info.specs.all()
    #     # 将每个库存商品的选项id加入到列表中
    #     spec_option_list = []  # [8,11]
    #     for spec in specs_list:
    #         spec_option_list.append(spec.option_id)
    #     skus_dict[tuple(spec_option_list)] = info.id  #
    skus_dict = {}
    skus = SKU.objects.all()
    for info in skus:
        specs_list = info.specs.all()
        spec_option_list = []
        for specc in specs_list:
            spec_option_list.append(specc.option_id)
        skus_dict[tuple(spec_option_list)] = info.id
    print(skus_dict)

    sku_option_list = sku.specs.order_by("spec_id")
    # [8,11]  8颜色规格  11内存
    option_id_list = [info.option_id for info in sku_option_list]
    spu = sku.spu
    specs = spu.specs.order_by("id")

    # 规格选项列表
    specs_list = []

    # 遍历所有的规格 并拿到该规格所对应的下标
    # 颜色==>0  内存==>1  [8,11]
    for index, spec in enumerate(specs):
        spec_dict = {
            # 规格名字
            "name": spec.name,
            # 所有选项列表
            "option_list": [],
        }
        # 遍历选项列表，得到每个选项对象
        # [8,9,10]
        for option in spec.options.all():
            # 复制当前库存商品的选项列表 [8,11] ==> [9,11]
            #  [9,11]  [10,11]  [8,12]
            # 根据该列表查找对应的库存商品
            option_id_list_temp = option_id_list[:]
            # 没有加select样式的选项[]
            option_id_list_temp[index] = option.id
            spec_dict["option_list"].append(
                {
                    # 取每个选项的名字
                    "name": option.value,
                    # 判断该选项是否在该库存商品所对应的选项列表中，返回True或者False
                    "selected": option.id in option_id_list,
                    # 跳转库存商品的id
                    "sku_id": skus_dict.get(tuple(option_id_list_temp)),
                }
            )
        specs_list.append(spec_dict)

    # 商品详情、商品评价、售后与包装
    # 热销排行

    context = {
        "categories": categories,
        "breadcrumb": breadcrumb,
        "sku": sku,
        "specs_list": specs_list
    }
    response= render(None, "detail.html", context)
    file_path = os.path.join(settings.BASE_DIR, 'static/%d.html'%sku_id)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(response.content.decode())